<?php

namespace app\forms\group;

use yii\db\Exception;
use app\forms\Model;
use app\models\Group;
use yii\web\HttpException;

/**
 * 组织 创建
 */
class CreateForm extends BaseForm
{

    public function rules()
    {
        $rules = parent::rules();
        return array_merge($rules, [
            ['name', 'unique', 'targetClass' => Group::class],
        ]);
    }

    /**
     * @param $param
     * @throws HttpException
     */
    public static function create($param)
    {
        $form = new self();
        $form->setAttributes($param);
        !$form->validate() ? $form->validateError() : '';

        try {
            $attr = $form->getAttributes();
            $attr['parent_id'] = $attr['parentId'];
            $model = new Group;
            $model->setAttributes($attr);
            $model->save(false);

        } catch (Exception $e) {
            $form->serverError();
        }

        $form->createOk();
    }
}